package io.cici.cc.mybatis.lite.sql_source;

import io.cici.cc.mybatis.lite.builder.Builder;
import io.cici.cc.mybatis.lite.builder.ParameterMappingTokenHandler;
import io.cici.cc.mybatis.lite.mapping.SqlSource;
import io.cici.cc.mybatis.lite.parse.TokenParser;
import io.cici.cc.mybatis.lite.session.Configuration;

import java.util.Map;
import java.util.StringTokenizer;

public class SqlSourceBuilder extends Builder {


    public SqlSourceBuilder(Configuration configuration) {
        super(configuration);
    }

    public static String removeExtraWhitespaces(String original) {
        StringTokenizer stringTokenizer = new StringTokenizer(original);
        StringBuilder sb = new StringBuilder();
        boolean hasMoreTokens = stringTokenizer.hasMoreTokens();
        while (hasMoreTokens) {
            sb.append(stringTokenizer.nextToken());
            hasMoreTokens = stringTokenizer.hasMoreTokens();
            if (hasMoreTokens) {
                sb.append(' ');
            }
        }
        return sb.toString();
    }

    public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
        TokenParser tokenParser = new TokenParser("#{", "}", parameterMappingTokenHandler);
        String sql;
        if (configuration.isShrinkWhitespacesInSql()) {
            sql = tokenParser.parse(removeExtraWhitespaces(originalSql));
        } else {
            sql = tokenParser.parse(originalSql);
        }
        return new StaticSqlSource(configuration, sql, parameterMappingTokenHandler.getParameterMappingList());
    }
}
